package org.skyfree.ghyll.tcard.control;

import org.eclipse.jface.viewers.TextCellEditor;
import org.eclipse.swt.events.MenuDetectEvent;
import org.eclipse.swt.events.MenuDetectListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Table;
import org.skyfree.ghyll.tcard.util.SpecialCharUtil;

public class SpecialCharTextCellEditor extends TextCellEditor implements MenuDetectListener, SelectionListener {

	public SpecialCharTextCellEditor(Table table) {
		super(table);
	}

	@Override
	protected Control createControl(Composite parent) {
		// TODO Auto-generated method stub
		super.createControl(parent);
		this.text.addMenuDetectListener(this);
		return this.text;
	}

	@Override
	public void menuDetected(MenuDetectEvent e) {
		this.text.setMenu(SpecialCharUtil.createDynamicMenu(this.text.getShell(),this));
		
	}

	@Override
	public void widgetDefaultSelected(SelectionEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void widgetSelected(SelectionEvent e) {
		if(e.getSource() instanceof MenuItem)
		{
			int position = this.text.getCaretPosition();
			String from = this.text.getText();
			MenuItem it = (MenuItem) e.getSource();
			String to = from.substring(0, position).concat(it.getText()).concat(from.substring(position));
			this.text.setText(to);
			this.text.setSelection(position+1);
			return;
		}
	}

	
}
